<template>
  <div class="w-1/1 h-1/1 server-svg-container" v-html="svgContent"></div>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted } from 'vue';
import type { ILeftAsideConfigItemPublicProps } from '../../store/types';

type ServerSvgRenderProps = {
  src: string;
  props: ILeftAsideConfigItemPublicProps;
};

const serverSvgProps = withDefaults(defineProps<ServerSvgRenderProps>(), {});
const originalSvgContent = ref<string>('');

// 获取原始SVG内容
const fetchSvgContent = async () => {
  try {
    const response = await fetch(serverSvgProps.src);
    if (response.ok) {
      const svgText = await response.text();
      // 验证是否为有效的SVG
      if (svgText.includes('<svg') && svgText.includes('</svg>')) {
        originalSvgContent.value = svgText;
      } else {
        throw new Error('Invalid SVG content');
      }
    } else {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
  } catch (error) {
    console.error('Failed to fetch SVG:', error);
    // 降级到img标签
    originalSvgContent.value = `<img src="${serverSvgProps.src}" style="width: 100%; height: 100%; object-fit: fill;" alt="SVG Image" />`;
  }
};

// 应用颜色修改的SVG内容
const svgContent = computed(() => {
  if (!originalSvgContent.value) return '';

  let modifiedSvg = originalSvgContent.value;

  // 应用填充颜色
  if (serverSvgProps.props.fill?.val) {
    const fillColor = serverSvgProps.props.fill.val as string;

    // 方法1: 替换所有path、circle、rect等元素的fill属性
    modifiedSvg = modifiedSvg.replace(/(<path[^>]*?)fill="[^"]*"/g, `$1fill="${fillColor}"`);
    modifiedSvg = modifiedSvg.replace(/(<circle[^>]*?)fill="[^"]*"/g, `$1fill="${fillColor}"`);
    modifiedSvg = modifiedSvg.replace(/(<rect[^>]*?)fill="[^"]*"/g, `$1fill="${fillColor}"`);
    modifiedSvg = modifiedSvg.replace(/(<polygon[^>]*?)fill="[^"]*"/g, `$1fill="${fillColor}"`);
    modifiedSvg = modifiedSvg.replace(/(<ellipse[^>]*?)fill="[^"]*"/g, `$1fill="${fillColor}"`);

    // 方法2: 为没有fill属性的元素添加fill
    modifiedSvg = modifiedSvg.replace(/(<path(?![^>]*fill=)[^>]*?)>/g, `$1 fill="${fillColor}">`);
    modifiedSvg = modifiedSvg.replace(/(<circle(?![^>]*fill=)[^>]*?)>/g, `$1 fill="${fillColor}">`);
    modifiedSvg = modifiedSvg.replace(/(<rect(?![^>]*fill=)[^>]*?)>/g, `$1 fill="${fillColor}">`);
    modifiedSvg = modifiedSvg.replace(
      /(<polygon(?![^>]*fill=)[^>]*?)>/g,
      `$1 fill="${fillColor}">`
    );
    modifiedSvg = modifiedSvg.replace(
      /(<ellipse(?![^>]*fill=)[^>]*?)>/g,
      `$1 fill="${fillColor}">`
    );

    // 方法3: 在svg根元素上设置默认fill
    if (!modifiedSvg.match(/<svg[^>]*fill=/)) {
      modifiedSvg = modifiedSvg.replace('<svg', `<svg fill="${fillColor}"`);
    }
  }

  // 应用描边颜色
  if (serverSvgProps.props.stroke?.val) {
    const strokeColor = serverSvgProps.props.stroke.val as string;

    // 替换现有的stroke属性
    modifiedSvg = modifiedSvg.replace(/(<path[^>]*?)stroke="[^"]*"/g, `$1stroke="${strokeColor}"`);
    modifiedSvg = modifiedSvg.replace(
      /(<circle[^>]*?)stroke="[^"]*"/g,
      `$1stroke="${strokeColor}"`
    );
    modifiedSvg = modifiedSvg.replace(/(<rect[^>]*?)stroke="[^"]*"/g, `$1stroke="${strokeColor}"`);
    modifiedSvg = modifiedSvg.replace(
      /(<polygon[^>]*?)stroke="[^"]*"/g,
      `$1stroke="${strokeColor}"`
    );
    modifiedSvg = modifiedSvg.replace(
      /(<ellipse[^>]*?)stroke="[^"]*"/g,
      `$1stroke="${strokeColor}"`
    );

    // 为没有stroke属性的元素添加stroke（仅当需要时）
    if (strokeColor !== 'none' && strokeColor !== 'transparent') {
      modifiedSvg = modifiedSvg.replace(
        /(<path(?![^>]*stroke=)[^>]*?)>/g,
        `$1 stroke="${strokeColor}">`
      );
      modifiedSvg = modifiedSvg.replace(
        /(<circle(?![^>]*stroke=)[^>]*?)>/g,
        `$1 stroke="${strokeColor}">`
      );
      modifiedSvg = modifiedSvg.replace(
        /(<rect(?![^>]*stroke=)[^>]*?)>/g,
        `$1 stroke="${strokeColor}">`
      );
      modifiedSvg = modifiedSvg.replace(
        /(<polygon(?![^>]*stroke=)[^>]*?)>/g,
        `$1 stroke="${strokeColor}">`
      );
      modifiedSvg = modifiedSvg.replace(
        /(<ellipse(?![^>]*stroke=)[^>]*?)>/g,
        `$1 stroke="${strokeColor}">`
      );
    }
  }

  // 确保SVG填满容器，允许自由拉伸
  // 移除所有可能影响拉伸的属性
  modifiedSvg = modifiedSvg.replace(/(<svg[^>]*?)style="[^"]*"/g, '$1');
  modifiedSvg = modifiedSvg.replace(/(<svg[^>]*?)width="[^"]*"/g, '$1');
  modifiedSvg = modifiedSvg.replace(/(<svg[^>]*?)height="[^"]*"/g, '$1');
  modifiedSvg = modifiedSvg.replace(/(<svg[^>]*?)preserveAspectRatio="[^"]*"/g, '$1');

  // 移除可能存在的min-width, min-height, max-width, max-height等CSS属性
  modifiedSvg = modifiedSvg.replace(/(<svg[^>]*?)\s+min-width="[^"]*"/g, '$1');
  modifiedSvg = modifiedSvg.replace(/(<svg[^>]*?)\s+min-height="[^"]*"/g, '$1');
  modifiedSvg = modifiedSvg.replace(/(<svg[^>]*?)\s+max-width="[^"]*"/g, '$1');
  modifiedSvg = modifiedSvg.replace(/(<svg[^>]*?)\s+max-height="[^"]*"/g, '$1');

  // 保留viewBox但确保preserveAspectRatio为none
  // viewBox定义了SVG的坐标系统，保留它以确保内容正确显示，但通过preserveAspectRatio="none"允许拉伸

  // 设置响应式样式，强制自由拉伸
  modifiedSvg = modifiedSvg.replace(
    '<svg',
    '<svg preserveAspectRatio="none" style="width: 100% !important; height: 100% !important; display: block;"'
  );

  // 调试输出
  if (serverSvgProps.src.includes('debug')) {
    console.log('SVG处理结果:', {
      原始长度: originalSvgContent.value.length,
      处理后长度: modifiedSvg.length,
      包含preserveAspectRatio_none: modifiedSvg.includes('preserveAspectRatio="none"'),
      包含width_100: modifiedSvg.includes('width: 100%')
    });
  }

  return modifiedSvg;
});

// 监听props变化重新获取SVG
watch(() => serverSvgProps.src, fetchSvgContent, { immediate: true });

onMounted(() => {
  fetchSvgContent();
});
</script>

<style scoped>
.server-svg-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.server-svg-container :deep(svg) {
  width: 100% !important;
  height: 100% !important;
  display: block !important;
}

.server-svg-container :deep(img) {
  width: 100%;
  height: 100%;
  object-fit: fill;
}
</style>
